<?php

namespace app\admin\model;

use think\Model;
use think\Db;


class Email extends Model
{

    // 表名
    protected $name = 'email';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'state_text'
    ];

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->bind('nickname');
    }

    public function price()
    {
        return $this->belongsTo('price', 'price_id', 'id', [], 'LEFT')->bind('name');
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            
            $custom = $row['custom'];
            if(!empty($custom)){
                $title = '寄往'.$custom;
                $receive_time = $custom;

            }else{
                $year_array = ['一年'=>1,'二年'=>2,'三年'=>3,'四年'=>4,'五年'=>5,'六年'=>6,'七年'=>7,'八年'=>8,'九年'=>9,'十年'=>10];

                $year = Db::name('price')->where(['id'=>$row['price_id']])->value('name');
                $title = '寄往'.$year.'后';
                $nowtime = time();
                $after_year = $year_array[$year];
                $receive_time = date('Y-m-d',strtotime("+".$after_year."year",$nowtime));
            }
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk],'title'=>$title,'receive_time'=>$receive_time]);
        });
    }
    
    public function getStateList()
    {
        return ['0' => __('State 0'), '1' => __('State 1')];
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }




}
